import csv
import json
import pandas as pd
import logging
import os
import time
from datetime import datetime

class Logging:
    """提供日志功能"""

    def __init__(self):
        self.logger = logging.getLogger(self.__class__.__name__)

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_formatter = logging.Formatter('[%(asctime)s] %(name)s %(levelname)s: %(message)s')
        console_handler.setFormatter(console_formatter)

        # 文件处理器
        # 确保目录存在
        os.makedirs(os.path.dirname('../logs/survey_project.log'), exist_ok=True)
        file_handler = logging.FileHandler('../logs/survey_project.log', encoding='utf-8')  # 日志文件名
        file_formatter = logging.Formatter('[%(asctime)s] %(name)s %(levelname)s: %(message)s')
        file_handler.setFormatter(file_formatter)

        if not self.logger.handlers:
            self.logger.addHandler(console_handler)
            self.logger.addHandler(file_handler)

        self.logger.setLevel(logging.DEBUG)

    def log_info(self, message: str):
        # self.logger.info(message)
        pass

    def log_warning(self, message: str):
        self.logger.warning(message)
        pass

    def log_error(self, message: str):
        self.logger.error(message)
        pass

    def log_debug(self, message: str):
        # self.logger.debug(message)
        pass

# 记录对话到CSV文件
def log_conversation_to_csv(question, response, filename='../logs/questions_answers.csv'):
    pass
    # # 确保目录存在
    # os.makedirs(os.path.dirname(filename), exist_ok=True)
    #
    # # 遍历response列表
    # for choice in response.choices:
    #     answer = ''
    #     if choice.message.content:
    #         answer = choice.message.content
    #
    #     if choice.message.tool_calls:
    #         # choice.message.tool_calls列表，获取function对象的arguments和name值
    #         for tool_call in choice.message.tool_calls:
    #             answer += f"{tool_call.function.name}：{tool_call.function.arguments}\n"
    #
    #     # 创建新的数据行
    #     new_row = pd.DataFrame({
    #         'question': [question],
    #         'answer': [answer],
    #         'finish_reason': [choice.finish_reason],
    #         'index': [choice.index],
    #         'timestamp': [time.time()],
    #         'response_time': [datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')]
    #     })
    #
    #     # 如果文件存在，追加数据；否则创建新文件
    #     if os.path.exists(filename):
    #         new_row.to_csv(filename, mode='a', header=False, index=False, encoding='utf-8-sig')
    #     else:
    #         new_row.to_csv(filename, index=False, encoding='utf-8-sig')